﻿@using System.Diagnostics
@using System.Text.Json

<ItemSelect Label="Datapoints" Items=points @bind-SelectedValue=pointsToLoad Changed=LoadData />

@if (pointsToLoad != 0)
{
    <ApexChart TItem="TimeSeries"
           Title="Value"
           Height="150"
           XAxisType="XAxisType.Datetime"
           @ref=chart>

        <ApexPointSeries TItem="TimeSeries"
                     Items="timeSeries.Take(pointsToLoad)"
                     Name="Value"
                     SeriesType="SeriesType.Line"
                     XValue="@(e => e.Date.ToUnixTimeMilliseconds())"
                     YValue="@( e=> e.Value)"
                     Stroke="@(new SeriesStroke { Width = 2, Color="#1F15E5"})" />
    </ApexChart>
}



@if (isLoading)
{
    <h3>Loading<span class="animated-dots"></span></h3>
}
else
{
    <h3>@message</h3>
}

@code {
    private ApexChart<TimeSeries> chart;
    private List<int> points = new List<int> { 0, 100, 1000, 5000, 10000, 15000, 20000 };
    private int pointsToLoad = 100;
    private List<TimeSeries> timeSeries = new TimeSeriesGenerator(25000).TimeSeries;
    private string message;
    private List<DataPoint<TimeSeries>> data;

    private bool isLoading;

    protected override void OnInitialized()
    {
        PopulateData();
    }

    private async Task LoadData()
    {
        if (pointsToLoad == 0)
        {
            message = "";
            return;
        }

        var sw = new Stopwatch();
        sw.Start();
        isLoading = true;

        await Task.Delay(1);

        PopulateData();
        message = $"{pointsToLoad} Points: Populate Data {sw.ElapsedMilliseconds.ToString("N0")}ms, ";
        sw.Restart();
        await chart.UpdateSeriesAsync(false);
        sw.Stop();

        message += $"Update Chart {sw.ElapsedMilliseconds.ToString("N0")}ms";
        isLoading = false;
    }

    private void PopulateData()
    {

        data = timeSeries.Take(pointsToLoad).Select(e => new DataPoint<TimeSeries>
            {
                X = e.Date,
                Y = e.Value,
                Items = new List<TimeSeries> { e }
            }).ToList();
    }
}